<template>
  <div class="container mx-auto px-4 py-6">
    <el-card class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="text-xl font-semibold">论文管理系统</h3>
          <el-button type="primary" @click="handleAddPaper">
            <el-icon><Plus /></el-icon>
            <span>提交论文</span>
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <div class="mb-4 flex flex-wrap gap-4">
        <el-input
            v-model="searchQuery"
            placeholder="搜索论文标题或作者"
            clearable
            style="width: 300px"
            @clear="handleSearchClear"
            @keyup.enter.native="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>

        <el-select
            v-model="statusFilter"
            placeholder="按状态筛选"
            clearable
            @change="handleStatusFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="草稿" :value="0" />
          <el-option label="已提交" :value="1" />
          <el-option label="待审核" :value="5" />
          <el-option label="需修改" :value="3" />
          <el-option label="已审核" :value="2" />
          <el-option label="已拒绝" :value="4" />
        </el-select>
      </div>

      <el-table
          :data="filteredPapers"
          stripe
          v-loading="loading"
          border
          @sort-change="handleSortChange"
          :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column label="论文标题" min-width="25%" sortable prop="paperTitle">
          <template #default="{ row }">
            <div class="flex items-center">
              <span
                  class="truncate mr-2 hover:text-blue-600 hover:underline cursor-pointer"
                  @click="handleViewPaper(row)"
              >
                {{ row.paperTitle }}
              </span>
              <el-tag v-if="row.firstAuthor" type="success" size="small" class="ml-1">一作</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="作者" min-width="20%">
          <template #default="{ row }">
            <el-tooltip :content="formatAuthors(row.authors, true)" placement="top">
              <span class="truncate">{{ formatAuthors(row.authors) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="提交日期" width="140" prop="createTime" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="120" prop="status" sortable>
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="plain">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="flex space-x-2 justify-center">
              <el-tooltip content="查看详情" placement="top">
                <el-button
                    size="small"
                    @click="handleViewPaper(row)"
                    type="primary"
                    plain
                >
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip content="下载论文" placement="top">
                <el-button
                    size="small"
                    type="primary"
                    @click="handleDownloadPaper(row)"
                >
                  <el-icon><Download /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip
                  :content="getEditTooltip(row.status)"
                  placement="top"
                  :disabled="canEditPaper(row.status)"
              >
                <el-button
                    size="small"
                    type="warning"
                    @click="handleEditPaper(row)"
                    :disabled="!canEditPaper(row.status)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>

              <el-tooltip
                  :content="getDeleteTooltip(row.status)"
                  placement="top"
                  :disabled="canDeletePaper(row.status)"
              >
                <el-button
                    size="small"
                    type="danger"
                    @click="handleDeletePaper(row)"
                    :disabled="!canDeletePaper(row.status)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>

      <div v-if="filteredPapers.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无论文" />
        <div class="mt-4 text-center">
          <el-button type="primary" @click="handleAddPaper">
            <el-icon><Plus /></el-icon>
            <span>立即提交</span>
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, View, Edit, Delete, Search, Download } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import {
  getMyPapers,
  deletePaper,
  downloadPaper
} from '@/api/paper.js';

const router = useRouter();
const authStore = useAuthStore();

// 数据状态
const papers = ref([]);
const loading = ref(false);
const currentSort = ref({ prop: 'createTime', order: 'descending' });
const searchQuery = ref('');
const statusFilter = ref('');

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 状态映射配置
const STATUS_CONFIG = {
  0: { text: '草稿', type: 'info', editable: true, deletable: true },
  1: { text: '已提交', type: '', editable: false, deletable: false },
  2: { text: '已审核', type: 'success', editable: false, deletable: false },
  3: { text: '需修改', type: 'warning', editable: true, deletable: false },
  4: { text: '已拒绝', type: 'danger', editable: false, deletable: false },
  5: { text: '待审核', type: 'primary', editable: false, deletable: false }
};

// 过滤后的论文列表
const filteredPapers = computed(() => {
  let result = [...papers.value];

  // 状态筛选
  if (statusFilter.value !== '') {
    result = result.filter(paper => paper.status === statusFilter.value);
  }

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(paper =>
        paper.paperTitle.toLowerCase().includes(query) ||
        formatAuthors(paper.authors).toLowerCase().includes(query)
    );
  }

  // 更新分页总数
  pagination.value.total = result.length;

  // 分页处理
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return result.slice(start, end);
});

// 工具函数
const formatAuthors = (authors, full = false) => {
  try {
    if (!authors) return '未设置';
    const authorList = JSON.parse(authors);
    return full
        ? authorList.map(a => `${a.name}${a.affiliation ? `(${a.affiliation})` : ''}`).join(', ')
        : authorList.map(a => a.name).join(', ');
  } catch {
    return authors || '未设置';
  }
};

const getStatusType = (statusCode) => {
  return STATUS_CONFIG[statusCode]?.type || 'info';
};

const getStatusText = (statusCode) => {
  return STATUS_CONFIG[statusCode]?.text || '未知状态';
};

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '--';
};

// 操作权限判断
const canEditPaper = (statusCode) => {
  // 学生只能编辑草稿(0)和需修改(3)状态的论文
  // 管理员/教师可能有更多权限，根据实际需求扩展
  return STATUS_CONFIG[statusCode]?.editable || false;
};

const canDeletePaper = (statusCode) => {
  // 仅草稿状态(0)可删除
  return STATUS_CONFIG[statusCode]?.deletable || false;
};

const getEditTooltip = (statusCode) => {
  return canEditPaper(statusCode)
      ? '编辑论文'
      : `无法编辑：${getStatusText(statusCode)}状态的论文`;
};

const getDeleteTooltip = (statusCode) => {
  return canDeletePaper(statusCode)
      ? '删除论文'
      : `无法删除：${getStatusText(statusCode)}状态的论文`;
};

// 获取论文列表
const fetchPapers = async () => {
  try {
    loading.value = true;
    const params = {
      sort: currentSort.value.prop,
      order: currentSort.value.order === 'descending' ? 'desc' : 'asc',
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      status: statusFilter.value || undefined,
      search: searchQuery.value || undefined
    };

    const response = await getMyPapers(params);
    papers.value = Array.isArray(response?.data) ? response.data : [];
    pagination.value.total = response?.total || papers.value.length;
  } catch (error) {
    console.error('获取论文列表失败:', error);
    handleApiError(error, '获取论文列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理API错误
const handleApiError = (error, defaultMessage = '操作失败') => {
  if (error.response?.status === 401) {
    authStore.logout();
    router.push('/login');
    ElMessage.warning('会话已过期，请重新登录');
  } else {
    ElMessage.error(error.response?.data?.message || defaultMessage);
  }
};

// 状态筛选变化处理
const handleStatusFilterChange = () => {
  pagination.value.currentPage = 1;
  fetchPapers();
};

// 排序变化处理
const handleSortChange = ({ prop, order }) => {
  currentSort.value = {
    prop,
    order: order || 'descending'
  };
  fetchPapers();
};

// 搜索处理
const handleSearch = () => {
  pagination.value.currentPage = 1;
  fetchPapers();
};

// 搜索清空处理
const handleSearchClear = () => {
  searchQuery.value = '';
  fetchPapers();
};

// 查看论文详情
const handleViewPaper = async (paper) => {
  if (!paper?.id) {
    ElMessage.error('无效的论文ID')
    return
  }

  try {
    // 确保认证初始化完成
    if (!authStore._initialized) {
      await authStore.initialize()
    }

    // 检查登录状态
    if (!authStore.isAuthenticated) {
      await router.push('/login')
      return
    }

    // 安全跳转
    await router.push({
      name: 'PaperDetail',
      params: { id: paper.id },
      query: { from: 'list' }
    })
  } catch (error) {
    console.error('跳转失败:', error)

    // 针对性错误提示
    if (error.message?.includes('roles')) {
      ElMessage.warning('权限信息加载失败，请刷新页面')
    } else {
      ElMessage.error('无法查看论文详情')
    }
  }
}
// 新增论文
const handleAddPaper = async () => {
  if (!authStore.isAuthenticated) {
    await router.push('/login');
    return;
  }

  try {
    await router.push({ name: 'SubmitPaper' });
  } catch (error) {
    console.error('跳转到提交页面失败:', error);
    ElMessage.error('无法访问提交页面');
  }
};

// 编辑论文
const handleEditPaper = async (paper) => {
  if (!paper?.id || !canEditPaper(paper.status)) {
    return ElMessage.warning(`当前状态(${getStatusText(paper.status)})不能编辑论文`);
  }

  if (!authStore.isAuthenticated) {
    await router.push('/login');
    return;
  }

  try {
    await router.push({
      name: 'PaperEdit',
      params: { paperId: paper.id }
    });
  } catch (error) {
    console.error('跳转到编辑页面失败:', error);
    ElMessage.error('无法编辑该论文');
  }
};

// 删除论文
const handleDeletePaper = async (paper) => {
  if (!paper?.id || !canDeletePaper(paper.status)) {
    return ElMessage.warning(`当前状态(${getStatusText(paper.status)})不能删除论文`);
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除《${paper.paperTitle}》吗？此操作不可恢复。`,
        '警告',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    await deletePaper(paper.id);
    ElMessage.success('删除成功');
    fetchPapers();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除论文失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 下载论文
const handleDownloadPaper = async (paper) => {
  if (!paper?.id) {
    ElMessage.error('无效的论文ID');
    return;
  }

  try {
    await downloadPaper(paper.id);
  } catch (error) {
    console.error('下载论文失败:', error);
    ElMessage.error('下载失败，请稍后再试');
  }
};

// 分页处理
const handleSizeChange = (newSize) => {
  pagination.value.pageSize = newSize;
  fetchPapers();
};

const handlePageChange = (newPage) => {
  pagination.value.currentPage = newPage;
  fetchPapers();
};

// 初始化
onMounted(async () => {
  try {
    await authStore.initialize();
    if (!authStore.isAuthenticated) {
      await router.push('/login');
      return;
    }
    await fetchPapers();
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error(`初始化失败: ${error.message || '请刷新页面重试'}`);
    if (!authStore.isAuthenticated) {
      await router.push('/login');
    }
  }
});
</script>

<style scoped>
.container {
  max-width: 1400px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.el-table {
  width: 100%;
}

.el-table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.el-table :deep(.el-tag) {
  font-weight: 500;
}

.el-button {
  transition: all 0.2s;
}

.el-button:hover {
  transform: translateY(-1px);
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .container {
    padding: 0 12px;
  }

  .el-table-column--selection {
    width: 40px;
  }

  .el-table-column--operate {
    width: 120px;
  }
}
</style>